import { addDialog } from "@/components/ReDialog";
import { useRouterNavigation } from "@/router/utils";
import { message } from "@/utils/message";
import type { PaginationProps } from "@pureadmin/table";
import { deviceDetection, getKeyList } from "@pureadmin/utils";
import dayjs from "dayjs";
import { type Ref, computed, h, onMounted, reactive, ref, toRaw } from "vue";
import editForm from "../form/index.vue";

// api
import {
  addResearch,
  delResearch,
  getResearchList,
  upResearch
} from "@/api/other/researchTeam";
import { getAchievTransList } from "@/api/research/achievTrans";
import { getOtherAwardList } from "@/api/research/award"; // 科研获奖
import { getPaperList } from "@/api/research/paper"; // 论文
import { getPatentList } from "@/api/research/patent"; // 专利
import { getProjectList } from "@/api/research/project"; // 横向、纵向项目
import { getUserList } from "@/api/system/user"; // 用户列表

export function useUser(tableRef: Ref) {
  const form = reactive({
    teamName: "",
    masterUserId: "",
    orderBy: "desc",
    examineStatus: "",
    pageNum: 1,
    pageSize: 10
  });
  const formRef = ref();
  const dataList = ref([]);
  const allUserList = ref([]);
  const loading = ref(true);
  const treeData = ref([]);
  const selectedNum = ref(0);
  const selectOpt = ref({
    hxList: [],
    zxList: [],
    lwList: [],
    zlList: [],
    hjList: [],
    cgzhList: []
  });
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "姓名",
      prop: "name",
      fixed: "left",
      minWidth: 120
    },
    {
      label: "工号",
      prop: "number",
      minWidth: 100
    },
    {
      label: "所属学院",
      prop: "college",
      minWidth: 120
    },
    {
      label: "所属系",
      prop: "collegeSystem",
      minWidth: 120
    },
    {
      label: "手机号",
      prop: "phone",
      minWidth: 100
    },
    {
      label: "电子邮箱",
      prop: "email",
      minWidth: 100
    },
    {
      label: "性别",
      prop: "sex",
      minWidth: 100,
      formatter: ({ sex }) => (sex == 1 ? "男" : "女")
    },
    {
      label: "民族",
      prop: "nationality",
      minWidth: 100
    },
    {
      label: "出生年月",
      prop: "birthday",
      minWidth: 100,
      formatter: ({ birthday }) =>
        birthday ? dayjs(birthday).format("YYYY-MM-DD") : ""
    },
    {
      label: "积分",
      prop: "score",
      minWidth: 100
    },
    {
      label: "学位",
      prop: "degree",
      minWidth: 100
    },
    {
      label: "学历",
      prop: "background",
      minWidth: 100
    },
    {
      label: "职称",
      prop: "titleNameList",
      minWidth: 100
    },
    {
      label: "职务",
      prop: "position",
      minWidth: 100
    },
    {
      label: "研究方向",
      prop: "direction",
      minWidth: 100
    },
    {
      label: "人员构成",
      prop: "bizType",
      minWidth: 100,
      formatter: ({ bizType }) => (bizType == 1 ? "校内人员" : "校外人员")
    },
    {
      label: "操作",
      fixed: "right",
      width: 220,
      slot: "operation"
    }
  ];

  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  // 查看商品详情
  const { push } = useRouterNavigation();
  const showDetail = row => {
    push({
      path: "/team/research/detail",
      query: { id: row.id }
    });
  };

  const handleDelete = async row => {
    await delResearch(row.id);
    message("删除成功", { type: "success" });
    onSearch();
  };

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    form.pageNum = val;
    onSearch();
  }

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    message(`已删除用户编号为 ${getKeyList(curSelected, "id")} 的数据`, {
      type: "success"
    });
    tableRef.value.getTableRef().clearSelection();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const { data } = await getResearchList(toRaw(form));
    dataList.value = data.records || [];
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.pageNum;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?) {
    let userIds = [];
    if (row?.userList) {
      userIds = row.userList.map(v => v.id);
    }
    addDialog({
      title: `${title}科研团队`,
      sureBtnLoading: true,
      props: {
        formInline: {
          id: row?.id ?? undefined,
          teamName: row?.teamName ?? "",
          decDate: row?.decDate ?? "",
          relyOnUnit: row?.relyOnUnit ?? "",
          masterUserId: row?.masterUserId ?? undefined,
          secretaryUserId: row?.secretaryUserId ?? undefined,
          userIds: userIds,
          baseInfo: row?.baseInfo ?? "",
          masterInfo: row?.masterInfo ?? "",
          longitudinalProjectIds: row?.longitudinalProjects
            ? row.longitudinalProjects.map(v => v.id)
            : [],
          horizontalProjectIds: row?.horizontalProjects
            ? row.horizontalProjects.map(v => v.id)
            : [],
          otherObtainRewardIds: row?.otherObtainRewards
            ? row.otherObtainRewards.map(v => v.id)
            : [],
          achievementTransformationIds: row?.transformations
            ? row.transformations.map(v => v.id)
            : [],
          paperIds: row?.papers ? row.papers.map(v => v.id) : [],
          patentIds: row?.patents ? row.patents.map(v => v.id) : [],
          resultInfo: row?.resultInfo ?? ""
        },
        userList: allUserList.value || [],
        selectOpt: selectOpt.value
      },
      width: "1000px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options, closeLoading }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline;
        console.log("curData", curData);
        function chores() {
          message("操作成功", {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
          loadAllUser();
        }
        FormRef.validate(async valid => {
          if (valid) {
            console.log("curData ", curData);
            // 表单规则校验通过
            if (title === "新增") {
              await addResearch(curData);
              chores();
            } else {
              await upResearch(curData);
              chores();
            }
          }
          closeLoading();
        });
      }
    });
  }

  // 获取用户
  const loadAllUser = async () => {
    let params = {
      pageNum: 1,
      pageSize: 500
    };
    let { data } = await getUserList(params);
    allUserList.value = data.records || [];
  };

  // 获取项目集合
  const loadListOpt = async () => {
    let params = {
      examineStatus: 1,
      orderBy: "desc",
      pageNum: 1,
      pageSize: 999
    };
    // 项目类型 1纵向 2横向
    getProjectList({ projectType: 2, ...params }).then(res => {
      selectOpt.value.hxList = res?.data?.records || [];
    });

    getProjectList({ projectType: 1, ...params }).then(res => {
      selectOpt.value.zxList = res?.data?.records || [];
    });

    getPaperList(params).then(res => {
      selectOpt.value.lwList = res?.data?.records || [];
    });

    getPatentList(params).then(res => {
      selectOpt.value.zlList = res?.data?.records || [];
    });

    getOtherAwardList(params).then(res => {
      selectOpt.value.hjList = res?.data?.records || [];
    });

    getAchievTransList(params).then(res => {
      selectOpt.value.cgzhList = res?.data?.records || [];
    });
  };

  onMounted(async () => {
    onSearch();

    // 获取所有用户
    loadAllUser();

    loadListOpt();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    treeData,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    allUserList,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    showDetail,
    handleDelete,
    handleSizeChange,
    handleCurrentChange
  };
}
